package org.idtem.utils.freeling;

import java.util.ArrayList;
import java.util.Collection;

import org.idtem.utils.constants.Constants.Common;

public class SentenciaFreeling {


	private ArrayList<TokenFreeling> tokens;
	private String _text;
	
	
	private SentenciaFreeling(ArrayList<String> tookensFreeling, int suggestStartPOs, String document)
	{
		this.tokens = new ArrayList<TokenFreeling>();
		for (String string : tookensFreeling) {
			TokenFreeling token = new TokenFreeling(string);
			tokens.add(token);
		}
		
		int index = 0;
		for (TokenFreeling token : this.tokens)
		{
			suggestStartPOs = token.setDocumentPosicion(suggestStartPOs, document, tokens, index);
			index++;
		}
		this._text = document.substring(tokens.get(0).getBegin(), tokens.get(tokens.size() - 1).getEnd() + 1);
	}
	
	public int getBegin() {
		if (tokens.size() > 0)
			return tokens.get(0).getBegin();
		try {
			throw new Exception();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	public int getEnd() {
		if (tokens.size() > 0)
			return tokens.get(tokens.size() - 1).getEnd();
		try {
			throw new Exception();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	public Collection<TokenFreeling> getTokens() {
		return tokens;
	}

	public static Collection<SentenciaFreeling> ObtenerSentencias(String document, String freelingOutput)
	{
		System.out.println(document);
	 	System.out.println(freelingOutput);
	
		ArrayList<SentenciaFreeling> result = new ArrayList<SentenciaFreeling>();		
		String[] lineas = freelingOutput.split(Common.NEWLINE);
		ArrayList<String> lineasFreelingOutput = new ArrayList<String>();
        int suggestStartPos = 0;
		for (int i = 0; i < lineas.length; i++) 
        {
        	String lineaFreeling = lineas[i];
        	if (lineaFreeling.trim().isEmpty() && lineasFreelingOutput.size() > 0)
        	{
        		SentenciaFreeling sentenciFree = new SentenciaFreeling(lineasFreelingOutput, suggestStartPos, document);
        		suggestStartPos = sentenciFree.getEnd();
        		result.add(sentenciFree);
        		lineasFreelingOutput = new ArrayList<String>();
        	}
        	else if (!lineaFreeling.trim().isEmpty())
        	{
        		lineasFreelingOutput.add(lineaFreeling);
        	}
       	}
        if (lineasFreelingOutput.size() > 0)
    	{
    		SentenciaFreeling sentenciFree = new SentenciaFreeling(lineasFreelingOutput, suggestStartPos, document);
    		result.add(sentenciFree);
    	}
        return result;
	}

	public String getText() {
		return _text;
	}
}
